package com.mvp.shq.washer.ui.shop.productDetail;

import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.jaeger.library.StatusBarUtil;
import com.mvp.shq.washer.APP;
import com.mvp.shq.washer.R;
import com.mvp.shq.washer.adapter.ShopBannerViewHolder;
import com.mvp.shq.washer.adapter.ShopProductBannerViewHolder;
import com.mvp.shq.washer.adapter.ShopSpecAdapter;
import com.mvp.shq.washer.base.BaseActivity;
import com.mvp.shq.washer.entity.User;
import com.mvp.shq.washer.entity.shop.Product;
import com.mvp.shq.washer.entity.shop.ProductComment;
import com.mvp.shq.washer.entity.shop.TotalOrderList;
import com.mvp.shq.washer.entity.shop.TotalOrderListData;
import com.mvp.shq.washer.entity.shop.result.ProductResult;
import com.mvp.shq.washer.rxbus.RxBus;
import com.mvp.shq.washer.rxbus.Subscribe;
import com.mvp.shq.washer.utils.DBUtil;
import com.mvp.shq.washer.utils.DataDictionary;
import com.mvp.shq.washer.utils.EventCode;
import com.mvp.shq.washer.utils.JumpUtil;
import com.mvp.shq.washer.utils.SpUtil;
import com.mvp.shq.washer.utils.StringUtils;
import com.mvp.shq.washer.utils.T;
import com.mvp.shq.washer.view.widget.SpecPopupWindow;
import com.orhanobut.logger.Logger;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zzhoujay.richtext.RichText;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ProductDetailActivity extends BaseActivity<Presenter, Model> implements ProductDetailConstract.View {

    public static final String PRODUCT_TYPE_SPU = "spu";
    public static final String PRODUCT_TYPE_SKU = "sku";
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.banner)
    MZBannerView banner;
    @BindView(R.id.tv_product_title)
    TextView tvProductTitle;
    @BindView(R.id.tv_price_1)
    TextView tvPrice1;
    @BindView(R.id.tv_price_2)
    TextView tvPrice2;
    @BindView(R.id.ll_money)
    LinearLayout llMoney;
    @BindView(R.id.tv_add)
    TextView tvAdd;
    @BindView(R.id.tv_integral)
    TextView tvIntegral;
    @BindView(R.id.ll_integral)
    LinearLayout llIntegral;
    @BindView(R.id.tv_express_type)
    TextView tvExpressType;
    @BindView(R.id.tv_sales_volume)
    TextView tvSalesVolume;
    @BindView(R.id.tv_choose_spec)
    TextView tvChooseSpec;
    @BindView(R.id.tv_product_des)
    TextView tvProductDes;
    @BindView(R.id.img_userface)
    ImageView imgUserface;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.rb_normal)
    RatingBar rbNormal;
    @BindView(R.id.tv_comment_time)
    TextView tvCommentTime;
    @BindView(R.id.tv_comment_content)
    TextView tvCommentContent;
    @BindView(R.id.tv_feedback_content)
    TextView tvFeedbackContent;
    @BindView(R.id.ll_feedback)
    LinearLayout llFeedback;
    @BindView(R.id.btn_more_comment)
    Button btnMoreComment;
    @BindView(R.id.img_collection)
    ImageView imgCollection;
    @BindView(R.id.ll_collection)
    LinearLayout llCollection;
    @BindView(R.id.ll_shop_car)
    LinearLayout llShopCar;
    @BindView(R.id.btn_add_to_car)
    Button btnAddToCar;
    @BindView(R.id.btn_buy_now)
    Button btnBuyNow;
    @BindView(R.id.tv_collection)
    TextView tvCollection;
    @BindView(R.id.tv_banner_count)
    TextView tvBannerCount;
    @BindView(R.id.tv_banner_current_positon)
    TextView tvBannerCurrentPosition;
    @BindView(R.id.comment_box)
    LinearLayout llCommentBox;
    @BindView(R.id.ll_comment_tittle)
    LinearLayout llCommentTitle;
    private boolean isCollection = false;
    private SpecPopupWindow popupWindow;
    private Product product;
    private int[] attrPositions;//每个规格选中的属性的下标
    private int attrSelectCount;//属性选中的数量
    private Product productSku;
    private User user;


    @Override
    public int getLayoutId() {
        return R.layout.activity_product_detail;
    }

    @Override
    public void initView() {
        StatusBarUtil.setColor(this, ContextCompat.getColor(context, R.color.money), 9);
        title.setText("商品详情");
        String productId = getIntent().getExtras().getString("productId");
        String type = getIntent().getExtras().getString("type");
        if (type.equals(PRODUCT_TYPE_SKU)){
            presenter.getProductInfo(productId);
        }else if (type.equals(PRODUCT_TYPE_SPU)){
            presenter.getProductInfoBySpu(productId);
        }
        setUserInfo();

    }

    @Subscribe(code = EventCode.UPDATE_USER)
    public void setUserInfo(){
        user = SpUtil.getUser();
    }


    @OnClick({R.id.back, R.id.btn_more_comment, R.id.rl_choose_spec,R.id.ll_collection, R.id.ll_shop_car, R.id.btn_add_to_car, R.id.btn_buy_now})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.rl_choose_spec:
                //选择规格
                if (product == null){
                    return;
                }
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 0.7f;
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getWindow().setAttributes(lp);
                if (popupWindow == null){
                    attrPositions = new int[product.getSpecList().size()];
                    //属性未选中,初始值为-1
                    for (int i=0;i<attrPositions.length;i++){
                        attrPositions[i] = -1;
                    }
                    attrSelectCount = 0;
                    popupWindow = new SpecPopupWindow(context, this, product.getSpecList(), new ShopSpecAdapter.OnAttrClickListener() {
                        @Override
                        public void onClick(int specPosition, int attrPosition) {
                            if (attrPositions[specPosition] == -1) {
                                //属性首次选择
                                attrSelectCount++;
                            }
                            attrPositions[specPosition] = attrPosition;
                            if (attrSelectCount == attrPositions.length) {
                                //所有属性选择完成
                                String attrs = "";
                                for (int i = 0; i < attrPositions.length; i++) {
                                    attrs += product.getSpecList().get(i).getAttrs().get(attrPositions[i]).getId();
                                    if (i != attrPositions.length - 1) {
                                        attrs += ",";
                                    }
                                }
                                showLoadingDialog(true);
                                presenter.getProductByAttr(product.getId(), attrs);
                            }

                        }
                    }, new SpecPopupWindow.OnBtnClickListener() {
                        @Override
                        public void onAddtoCartClick() {
                            addToCart();
                        }

                        @Override
                        public void onBuyNowClick() {
                            if (user == null){
                                JumpUtil.toLogin(context);
                                return;
                            }
                            if (productSku == null){
                                T.show("请先选择规格");
                                return;
                            }
                            JumpUtil.toOrderSumbit(context,EventCode.SHOP_PAGETYPE_0);
                        }

                        @Override
                        public void onNumChange(int num) {
                            if (productSku == null){
                                T.show("请先选择规格");
                                return;
                            }
                            productSku.setByNum(num);
                        }
                    });

                }
                popupWindow.showAtLocation(back, Gravity.BOTTOM,0,0);
                break;
            case R.id.btn_more_comment:
                JumpUtil.toProductComment(context,product.getId());
                break;
            case R.id.ll_collection:
                //收藏
                if (user == null){
                    JumpUtil.toLogin(context);
                    return;
                }
                if (isCollection){
                    //取消收藏
                    presenter.delCollectProduct(product.getId());
                }else {
                    //收藏
                    presenter.collectProduct(product.getId());
                }
                break;
            case R.id.ll_shop_car:
                JumpUtil.toShopCar(context);
                break;
            case R.id.btn_add_to_car:
//                if (productSku == null){
//                    T.show("请先选择规格");
//                    return;
//                }
//                productSku.setByNum(1);
//                DBUtil.getInstance().insertOrUpdateProduct(productSku);
//                T.show("已加入购物车");
                addToCart();
                break;
            case R.id.btn_buy_now:
                if (productSku == null){
                    T.show("请先选择规格");
                    return;
                }
                if (user == null){
                    JumpUtil.toLogin(context);
                    return;
                }
                JumpUtil.toOrderSumbit(context,EventCode.SHOP_PAGETYPE_0);
                break;
        }
    }

    private void addToCart(){
        if (productSku == null){
            T.show("请先选择规格");
            return;
        }
        productSku.setByNum(1);
        DBUtil.getInstance().insertOrUpdateProduct(productSku);
        T.show("已加入购物车");
    }

    @Subscribe(code = EventCode.SHOP_SEND_PRODUCT_ON_PRODUCT_DETAIL)
    public void sendProduct(){
        Logger.d("提交订单-------------");
        List<Product> list = new ArrayList<>();
        list.add(productSku);
        TotalOrderListData result = new TotalOrderListData(productSku.getCompanyId(),list);
        List<TotalOrderListData> productResultList=new ArrayList<>();
        productResultList.add(result);
        Logger.d("订单为："+productResultList.size());
        RxBus.get().send(EventCode.SHOP_SUMBIT_ORDER,new TotalOrderList(productResultList));
    }

    @Override
    public void onResume() {
        super.onResume();
        banner.start();
    }

    @Override
    public void onPause() {
        super.onPause();
        banner.pause();
    }

    /**
     * 设置banner
     * @param list
     */
    private void initBanner(List<String> list){
        for (int i=0;i<list.size();i++){
            String str = DataDictionary.SHOP_IMG_BASE_URL + list.get(i);
            list.set(i,str);
        }
        banner.setPages(list, new MZHolderCreator<ShopProductBannerViewHolder>() {
            @Override
            public ShopProductBannerViewHolder createViewHolder() {
                return new ShopProductBannerViewHolder();
            }
        });
        tvBannerCount.setText("/"+(list.size()));
        tvBannerCurrentPosition.setText("1");
        banner.addPageChangeLisnter(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tvBannerCurrentPosition.setText(""+(position+1));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        banner.setIndicatorVisible(false);
        banner.setDelayedTime(3000);
        banner.setDuration(3000);
    }


    private void setCommentContent(ProductComment comment){
        if (comment == null){
            llCommentBox.setVisibility(View.GONE);
            llCommentTitle.setVisibility(View.GONE);
            btnMoreComment.setVisibility(View.GONE);
            return;
        }
        if ("1".equals(comment.getAnonym())){
            tvUsername.setText(comment.getAnonymName());
        }else if ("0".equals(comment.getAnonym())){
            tvUsername.setText(comment.getUserNickname());
        }
        rbNormal.setRating((float) comment.getStar());
        tvCommentTime.setText(comment.getCreateDate());
        tvCommentContent.setText(comment.getContent());
        if (comment.getReplyInfo() == null || TextUtils.isEmpty(comment.getReplyInfo())){
            llFeedback.setVisibility(View.GONE);
        }else {
            llFeedback.setVisibility(View.VISIBLE);
            tvFeedbackContent.setText(comment.getReplyInfo());
        }
        tvFeedbackContent.setText(comment.getCompanyName());
        String imgUrl = comment.getFaceurl();
        Logger.d("评论图片地址:"+imgUrl);
        imageUtil.loadUrlImage(imgUrl,imgUserface);
    }

    @Override
    public void getProductInfoS(Product p) {
        product = p;
        initBanner(product.getImgList());
        tvProductTitle.setText(product.getProductName());
        setCommentContent(product.getComment());
        RichText.fromHtml(product.getProductDes()).bind(this).into(tvProductDes);
        isCollection = product.getIsCollect().equals("1");
        initCollect();
        llMoney.setVisibility(View.VISIBLE);
        tvAdd.setVisibility(View.GONE);
        llIntegral.setVisibility(View.GONE);
        tvPrice1.setText(product.getPriceRange());
        tvPrice2.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RichText.recycle();
    }

    private void initCollect(){
        if (isCollection){
            tvCollection.setTextColor(ContextCompat.getColor(context,R.color.money));
            imgCollection.setImageResource(R.mipmap.commodity_collection__selected);
        }else {
            tvCollection.setTextColor(ContextCompat.getColor(context,R.color.shop_more));
            imgCollection.setImageResource(R.mipmap.commodity_collection_pressed);
        }
    }

    @Override
    public void getProductByAttrS(Product p) {
        if (p == null){
            T.show("暂无该商品");
            return;
        }
        productSku = p;
        productSku.setByNum(1);
        popupWindow.setProduct(productSku);
        tvChooseSpec.setText(productSku.getSpecText());
        tvSalesVolume.setText(productSku.getSellNum()+"件");
        BigDecimal decimal = new BigDecimal("0");
        int type = 0;
        String money1 = "",money2 = "",integral = "";
        if (productSku.getPayMode().equals(DataDictionary.PAY_MODE_CASH_AND_INTEGRAL)){
            type = 0;
            money1 = Math.floor(productSku.getCashPrice())+"";
            money2 = StringUtils.BigDecimalToStr(BigDecimal.valueOf(productSku.getCashPrice()));
            integral = (int)product.getIntegralPrice()+"";
        }else if (productSku.getPayMode().equals(DataDictionary.PAY_MODE_CASH)){
            type = 2;
            money1 = Math.floor(productSku.getCashPrice())+"";
            money2 = StringUtils.BigDecimalToStr(BigDecimal.valueOf(productSku.getCashPrice()));
        }else {
            type = 1;
            integral = (int)product.getIntegralPrice()+"";
        }
        switch (type){
            case 0:
                //现金加积分购买
                llMoney.setVisibility(View.VISIBLE);
                tvAdd.setVisibility(View.VISIBLE);
                llIntegral.setVisibility(View.VISIBLE);
                //tvIntegralPrompt.setVisibility(View.GONE);
                tvPrice1.setText(money1);
                tvPrice2.setText(money2);
                tvPrice2.setVisibility(View.VISIBLE);
                tvIntegral.setText(integral);
                break;
            case 1:
                //积分购买
                llMoney.setVisibility(View.GONE);
                tvAdd.setVisibility(View.GONE);
                llIntegral.setVisibility(View.VISIBLE);
                //tvIntegralPrompt.setVisibility(View.VISIBLE);
                tvIntegral.setText(integral);
                break;
            case 2:
                //现金购买
                llMoney.setVisibility(View.VISIBLE);
                tvAdd.setVisibility(View.GONE);
                llIntegral.setVisibility(View.GONE);
                //tvIntegralPrompt.setVisibility(View.GONE);
                tvPrice1.setText(money1);
                tvPrice2.setText(money2);
                tvPrice2.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void collectProductS() {
        isCollection = true;
        tvCollection.setTextColor(ContextCompat.getColor(context,R.color.money));
        imgCollection.setImageResource(R.mipmap.commodity_collection__selected);
        RxBus.get().send(EventCode.SHOP_UPDATE_COLLECT_AND_ORDER_NUM);
    }

    @Override
    public void delCollectProductS() {
        isCollection = false;
        tvCollection.setTextColor(ContextCompat.getColor(context,R.color.shop_more));
        imgCollection.setImageResource(R.mipmap.commodity_collection_pressed);
        RxBus.get().send(EventCode.SHOP_UPDATE_COLLECT_AND_ORDER_NUM);
    }
}
